//
//  MainTabBarController.swift
//  Weibo
//
//  Created by 伍银荣 on 2021/12/14.
//  Copyright © 2021 com.WYR. All rights reserved.
//

import UIKit

class MainTabBarController: UITabBarController {

    override func viewDidLoad() {
        super.viewDidLoad()
        //添加控制器,并不会创建 tabBar 中的按钮
        addAllChildControllers()
        print(tabBar.subviews)
        setupComposeButton()
       
    }
    override func viewWillAppear(_ animated: Bool) {
        //调用此方法会创建 tabBar 中的所有控制器对应的按钮
        super.viewWillAppear(animated)
        //将撰写按钮弄到最前面
        tabBar.bringSubviewToFront(composeButton)
    }
    //MARK: - 懒加载控件
    private lazy var composeButton: UIButton = {
        //自定义样式的按钮
       let button = UIButton(type: UIButton.ButtonType.contactAdd)
        button.backgroundColor = UIColor.red
        return button
    }()

}

// MARK: - 设置界面
extension MainTabBarController {
    //设置撰写按钮
    private func setupComposeButton() {
        tabBar.addSubview(composeButton)
        //获取tabBarController中的子控件按钮个数
        let count = children.count
        //设置按钮的宽度
        let w = tabBar.bounds.size.width / CGFloat(count)
        //设置按钮的frame
        composeButton.frame = CGRect(x: w * 2, y: 0, width: w, height: tabBar.bounds.height)
    }
    
    //添加所有控制器
    private func addAllChildControllers() {
        addChildViewController(vc: HomeViewController(), title: "首页", imageName: "shouye")
        addChildViewController(vc: MessageViewController(), title: "消息", imageName: "xiaoxi")
        addChild(UIViewController())
        addChildViewController(vc: DiscoverViewController(), title: "发现", imageName: "faxian")
        addChildViewController(vc: ProfileViewController(), title: "我", imageName: "wode")
    }
    
    //添加控制器
    private func addChildViewController(vc: UIViewController, title: String, imageName: String) {
        //设置标题 - 由内至外设置的
        vc.title = title
        vc.tabBarItem.image = UIImage(named: imageName)
        let nav = UINavigationController(rootViewController: vc)
        addChild(nav)
    }
}
